package eu.daxiongmao.skills.ws;

import eu.daxiongmao.skills.dao.db.UserDbDao;
import eu.daxiongmao.skills.model.User;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

/**
 * User REST web-service.<br/>
 * To perform simple requests again the "users" table.
 *
 * @author guillaume
 * @version 1.0 - April 2014
 */
@Stateless
@Path("users")
public class UserRestWs {

    private static final Logger LOGGER = Logger.getLogger(UserRestWs.class.getName());

    @Context
    private UriInfo context;

    @EJB
    private UserDbDao usersDbDao;

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getHtml() {
        return "<html>"
                + "<head> "
                + "<title>REST WS: users</title>"
                + "</head>"
                + "<body>"
                + "<h1>Users REST WS</h1>"
                + "<p>If you can see that text then the REST service has been deployed!</p>"
                + "</body>"
                + "</html>";
    }

    @GET
    @Path("getAll")
    @Produces(MediaType.TEXT_PLAIN)
    public String getAll() {
        List<User> target = usersDbDao.findAll();

        StringBuilder log = new StringBuilder();
        for (User temp : target) {
            log.append(temp.toString()).append("\n");
        }

        return log.toString();
    }

    @GET
    @Path("list")
    @Produces(MediaType.TEXT_PLAIN)
    public String listUsers(
            @DefaultValue("0")
            @QueryParam("page") Integer page,
            @DefaultValue("20")
            @QueryParam("pageSize") Integer pageSize,
            @DefaultValue("id")
            @QueryParam("sortField") String sortField,
            @DefaultValue("asc")
            @QueryParam("sortDirection") String sortDirection) {

        // Process sort order
        boolean ascendingDirection;
        if (sortDirection == null || sortDirection.equalsIgnoreCase("asc")) {
            ascendingDirection = true;
        } else {
            ascendingDirection = false;
        }

        // Process start point
        int firstResult = 0;
        if (page > 0) {
            firstResult = page * pageSize;
        }

        // Get results
        List<User> target = usersDbDao.findAll(firstResult, pageSize, sortField, ascendingDirection);
        StringBuilder log = new StringBuilder();
        for (User temp : target) {
            log.append(temp.toString()).append("\n");
        }

        return log.toString();
    }
}
